package com.feel.mall.goodsservice.controller;

import com.feel.mall.common.bean.Comment;
import com.feel.mall.common.bean.RespBean;
import com.feel.mall.common.exception.FeelException;
import com.feel.mall.common.service.CommentService;
import com.feel.mall.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Author: 刘永钦
 * @Description:
 */
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    /**
     * 获取评论信息
     */
    @GetMapping
    public RespBean getList(Comment comment) {
        List<Comment> list = commentService.getInfo(comment);
        return RespBean.ok("查询成功", list);
    }

    /**
     * 发表评论
     */
    @PostMapping
    public RespBean addInfo(@RequestBody Comment comment, @RequestHeader("token") String token) {
        // 解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");

        comment.setUserId(userId);

        Boolean b = commentService.addInfo(comment);
        return b ? RespBean.ok("发表成功") : RespBean.error("发表失败");
    }

    /**
     * 删除评论
     */
    @DeleteMapping
    public RespBean delInfo(Integer commentId, @RequestHeader("token") String token) throws FeelException {
        // 解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");

        Boolean b = commentService.dellInfo(commentId, userId);

        return b ? RespBean.ok("删除成功") : RespBean.error("删除失败");
    }

    /**
     * 更新评论
     */
    public RespBean updateInfo(Comment comment, @RequestHeader("token") String token) throws FeelException {
        // 解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");

        Boolean b = commentService.updateInfo(comment, userId);

        return b ? RespBean.ok("更新成功") : RespBean.error("更新失败");
    }
}
